﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Model
{
    [ObjectEvent]
    public class StartConfigComponentEvent : ObjectEvent<StartConfigComponent>, IAwake<string,int>
    {
        public void Awake(string a,int b)
        {
            this.Get().Awake(a, b);
        }
    }

    public  class StartConfigComponent : Component
    {
        private Dictionary<int, StartConfig> configDict;

        public StartConfig StartConfig { get; set; }
        
        public StartConfig RealmConfig { get; set; }

        public List<StartConfig> GateConfigs { get; set; }

        public StartConfig DBConfig { get; set; }

        public StartConfig WebService { get; set; }

        public void Awake(string path,int appId)
        {
            this.configDict = new Dictionary<int, StartConfig>();
            this.GateConfigs = new List<StartConfig>();

            string json = File.ReadAllText(path);

            LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(json);

            foreach (LitJson.JsonData item in jsonData)
            {
                StartConfig startConfig = new StartConfig
                {
                    AppId = (int)item["AppId"],
                    AppType = (AppType)Enum.Parse(typeof(AppType),item["AppType"].ToString()),
                    ServerIP = item["ServerIP"].ToString(),
                    OuterIP = item["OuterIP"].ToString(),
                    InnerIP = item["InnerIP"].ToString(),
                    IsRun = bool.Parse( item["IsRun"].ToString())
                };
                this.configDict.Add(startConfig.AppId, startConfig);

                if (startConfig.AppType.Is(AppType.Gate))
                {
                    this.GateConfigs.Add(startConfig);
                }

                if (startConfig.AppType.Is(AppType.DB))
                {
                    this.DBConfig = startConfig;
                }

                if(startConfig.AppType.Is(AppType.Realm))
                {
                    this.RealmConfig = startConfig;
                }
            }
            this.StartConfig = Get(appId);
        }

        public StartConfig Get(int id)
        {
            try
            {
                return this.configDict[id];
            }
            catch (Exception)
            {
                throw new Exception("not found startConfig:" + id);
            }
        }

        public StartConfig[] GetAll()
        {
            return this.configDict.Values.ToArray();
        }
    }
}